package com.hdax.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdax.cart.config.MyThreadConfig;
import com.hdax.cart.feign.ProductFeignService;
import com.hdax.cart.interceptor.CartInterceptor;
import com.hdax.cart.service.CartService;
import com.hdax.cart.vo.Cart;
import com.hdax.cart.vo.CartItem;
import com.hdax.cart.vo.SkuInfoVo;
import com.hdax.cart.vo.UserInfoTo;
import com.hdax.common.constant.AuthConstant;
import com.hdax.common.to.MemberEntity;
import com.hdax.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    private final String CART_PREFIX="gulimall:cart:";


    /**
     * 添加到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws JsonProcessingException, ExecutionException, InterruptedException {
        //获取redis中的数据，如果登录了获取登录用户的购物车信息，如果没有登录获取本地的购物车数据
        /**
         * 获取缓存中的map
         */
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //购物车没有当前要添加的商品
            CartItem cartItem=new CartItem();
            CompletableFuture<Void> skuInfo1 = CompletableFuture.runAsync(() -> {
                /**
                 * 远程查询当前要添加的商品信息
                 */
                R info = productFeignService.info(skuId);
                Object skuInfo = info.get("skuInfo");
                SkuInfoVo skuInfoVo = null;
                try {
                    skuInfoVo = objectMapper.readValue(objectMapper.writeValueAsString(skuInfo), SkuInfoVo.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImges(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoVo.getPrice());
            }, threadPoolExecutor);
            /**
             * 远程查出当前商品的属性分组信息
             */
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, threadPoolExecutor);
            CompletableFuture.allOf(skuInfo1,voidCompletableFuture).get();
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }else {
            //购物车有此商品，修改缓存中该商品的数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            Integer count = cartItem.getCount();
            cartItem.setCount(count+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 根据skuid查询添加的购物车商品信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        //根据登录状态，获取缓存中的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    /**
     * 获取购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, JsonProcessingException, InterruptedException {
        UserInfoTo userInfoTo1 = CartInterceptor.toThreadLocal.get();
        Cart cart=new Cart();
        if(userInfoTo1.getUserId()!=null){
            //登录
            String cartKey= CART_PREFIX+userInfoTo1.getUserId();
            //临时购物车的数据
            List<CartItem> cartItem = getCartItem(CART_PREFIX+userInfoTo1.getUserKey());
            //和临时购物车和登录购物车[合并购物车]
            if(cartItem!=null){
                for (CartItem item : cartItem) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //临时购物车和用户购物车合并之后，删除本地的购物车
                clearCart(CART_PREFIX+userInfoTo1.getUserKey());
            }
            //获取用户的购物车
            List<CartItem> cartItem1 = getCartItem(cartKey);
            cart.setItems(cartItem1);
        }else {
            //没登
            //获取redis存储购物车的key
            String cartKey = CART_PREFIX+userInfoTo1.getUserKey();
            //临时购物车的所有数据
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);
        }
        return cart;
    }


    /**
     * 删除购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        Boolean delete = stringRedisTemplate.delete(cartKey);

    }

    /**
     * 修改购物车的选中状态
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        //获取当前的购物车(根据是否有没有登录来获取)
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 修改购物车商品的数量
     * @param skuId
     * @param num
     */

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem1 = getCartItem(skuId);
        cartItem1.setCount(num);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem1));
    }

    /**
     * 删除购物车
     * @param skuId
     */
    @Override
    public void delCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取购物车所有选中的数据
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        System.out.println("当前登录的用户id"+userInfoTo);
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            System.out.println("当前登录的用户id"+userInfoTo.getUserId());
            List<CartItem> cartItem = getCartItem(CART_PREFIX + userInfoTo.getUserId());
            List<CartItem> collect = cartItem.stream().map(item -> {
                //将价格更新为最新的价格
//                item.setPrice(productFeignService.getPrice(item.getSkuId()));
                return item;
            }).filter(item -> item.getCheck()).collect(Collectors.toList());
            //获取被选中的购物项
            return collect;
        }
    }


    /**
     * 获取购物车里面的数据
     */
    private List<CartItem>  getCartItem(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values!=null && values.size()>0){
            return values.stream().map((item) -> {
                String str = (String) item;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
        }
        return null;
    }


    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps(){
        //得到拦截器的用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey="";
        if(userInfoTo.getUserId()!=null){
            cartKey = CART_PREFIX+userInfoTo.getUserId();
        }else{
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }
        //通过key获取缓存中的hash内容
        BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return stringObjectObjectBoundHashOperations;
    }
}
